// 格式化时间为 MM:SS 格式
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 初始化视频播放器
function initVideoPlayer(videoId, placeholderId, controlsId, playBtnId, controlPlayBtnId, 
                        currentTimeId, totalTimeId, progressBarId, speedDisplayId) {
    const video = document.getElementById(videoId);
    const placeholder = document.getElementById(placeholderId);
    const controls = document.getElementById(controlsId);
    const playBtn = document.getElementById(playBtnId);
    const videoPlayBtn = document.getElementById(controlPlayBtnId);
    const currentTimeEl = document.getElementById(currentTimeId);
    const totalTimeEl = document.getElementById(totalTimeId);
    const progressBar = document.getElementById(progressBarId);
    const speedDisplay = document.getElementById(speedDisplayId);
    const progressContainer = progressBar.parentElement;
    const speedOptions = controls.querySelectorAll('.speed-option');
    
    // 拖动进度条相关变量
    let isDragging = false;
    
    // 当视频元数据加载完成后获取总时长
    video.addEventListener('loadedmetadata', function() {
        totalTimeEl.textContent = formatTime(video.duration);
    });
    
    // 播放按钮点击事件
    playBtn.addEventListener('click', function() {
        placeholder.classList.add('hidden');
        controls.classList.remove('hidden');
        video.play();
        updatePlayIcon();
    });
    
    // 控制栏播放按钮
    videoPlayBtn.addEventListener('click', function() {
        togglePlay();
    });
    
    // 切换播放/暂停状态
    function togglePlay() {
        if (video.paused) {
            video.play();
        } else {
            video.pause();
        }
        updatePlayIcon();
    }
    
    // 更新播放按钮图标
    function updatePlayIcon() {
        if (video.paused) {
            videoPlayBtn.innerHTML = '<i class="fa fa-play"></i>';
        } else {
            videoPlayBtn.innerHTML = '<i class="fa fa-pause"></i>';
        }
    }
    
    // 视频播放进度更新
    video.addEventListener('timeupdate', function() {
        if (!isDragging) {
            // 更新当前时间显示
            currentTimeEl.textContent = formatTime(video.currentTime);
            
            // 更新进度条
            const progress = (video.currentTime / video.duration) * 100;
            progressBar.style.width = `${progress}%`;
        }
    });
    
    // 视频结束时显示占位符
    video.addEventListener('ended', function() {
        placeholder.classList.remove('hidden');
        controls.classList.add('hidden');
        updatePlayIcon();
    });
    
    // 点击进度条跳转
    progressContainer.addEventListener('click', function(e) {
        updateProgressFromClick(e);
    });
    
    // 开始拖动进度条
    progressContainer.addEventListener('mousedown', function(e) {
        isDragging = true;
        updateProgressFromClick(e);
        video.pause();
    });
    
    // 拖动进度条
    document.addEventListener('mousemove', function(e) {
        if (isDragging) {
            updateProgressFromClick(e);
        }
    });
    
    // 结束拖动进度条
    document.addEventListener('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            video.play();
        }
    });
    
    // 从点击位置更新进度
    function updateProgressFromClick(e) {
        const rect = progressContainer.getBoundingClientRect();
        const pos = (e.clientX - rect.left) / rect.width;
        const newTime = pos * video.duration;
        
        // 限制在有效范围内
        if (newTime >= 0 && newTime <= video.duration) {
            video.currentTime = newTime;
            currentTimeEl.textContent = formatTime(newTime);
            progressBar.style.width = `${pos * 100}%`;
        }
    }
    
    // 播放速度控制
    speedOptions.forEach(option => {
        option.addEventListener('click', function(e) {
            e.stopPropagation();
            const speed = parseFloat(this.getAttribute('data-speed'));
            video.playbackRate = speed;
            speedDisplay.textContent = `${speed}x`;
            
            // 高亮当前选中的速度
            speedOptions.forEach(opt => opt.classList.remove('bg-primary/20'));
            this.classList.add('bg-primary/20');
        });
    });
    
    // 显示控制栏的鼠标事件
    const videoContainer = video.parentElement;
    let hideControlsTimeout;
    
    function showControls() {
        controls.classList.remove('hidden');
        clearTimeout(hideControlsTimeout);
        
        // 播放时自动隐藏控制栏
        if (!video.paused) {
            hideControlsTimeout = setTimeout(() => {
                controls.classList.add('hidden');
            }, 3000);
        }
    }
    
    videoContainer.addEventListener('mousemove', showControls);
    videoContainer.addEventListener('click', function(e) {
        // 点击视频区域切换播放状态
        if (!e.target.closest('button') && !e.target.closest('.speed-option')) {
            togglePlay();
        }
    });
    
    // 初始化显示1.0x速度
    speedDisplay.textContent = '1.0x';
}

// 页面加载完成后初始化所有视频播放器
document.addEventListener('DOMContentLoaded', function() {
    // 初始化注册视频播放器
    initVideoPlayer(
        'register-video', 
        'register-placeholder', 
        'register-controls', 
        'play-register', 
        'register-play-btn',
        'current-time',
        'total-time',
        'progress-bar',
        'register-speed'
    );
    
    // 初始化密码重置视频播放器
    initVideoPlayer(
        'password-video', 
        'password-placeholder', 
        'password-controls', 
        'play-password', 
        'password-play-btn',
        'password-current-time',
        'password-total-time',
        'password-progress-bar',
        'password-speed'
    );
});
